package com.nononsenseapps.feeder.mobile.ui

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.Window
import androidx.fragment.app.FragmentActivity
import com.nononsenseapps.feeder.mobile.ui.reader.sample.MarkDownViewFragment
import com.nononsenseapps.feeder.mobile.ui.reader.sample.MarkDownViewFragment.Companion.ARG_OPEN_MD_URI
import com.nononsenseapps.feeder.util.naiveFindUrlLink

class MarkDownViewActivity: FragmentActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (supportFragmentManager.findFragmentById(Window.ID_ANDROID_CONTENT) == null) {
            supportFragmentManager.beginTransaction()
                .add(Window.ID_ANDROID_CONTENT, MarkDownViewFragment().apply {
                    arguments = Bundle().apply {
                        putParcelable(ARG_OPEN_MD_URI, intent.data)
                        if(intent?.data == null){
                            intent?.let{
                                val shardStr = (it.dataString ?: it.getStringExtra(Intent.EXTRA_TEXT) ?: "").trim()
                                // Link
                                val urlLink = naiveFindUrlLink(shardStr) ?: shardStr
                                putParcelable(ARG_OPEN_MD_URI, Uri.parse(urlLink))
                            }
                        }
                    }
                })
                .commitNowAllowingStateLoss()
        }
    }
}